import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/net/post_request.dart';

import '../a_yyt/models/floor_list_entity.dart';
import '../a_yyt/models/medical_elder_entity.dart';
import '../config/global_configs.dart';
import '../model/building_model.dart';
import '../model/customer_info_model.dart';
import '../net/api/http_api.dart';

class SelectOldViewModel extends BaseListViewModel<MedicalElderInfo> {
  final bool isMeal;
  Function(MedicalElderInfo old)? selectListener;
  SelectOldViewModel(BuildContext context,{this.isMeal = false,this.selectListener,this.useLastFilter = false}) : super(context);

  var buildingModel = BuildingModel();
  List<FloorEntity> buildingList = [];
  FloorEntity? selectBuilding;
  List<FloorInfo> floorList = [];
  FloorInfo? selectFloor;

  var searchName = "";

  var customerModel = CustomerInfoModel();

  bool useLastFilter = false;

  @override
  Future<List<MedicalElderInfo>> requestListData() async {
    if (buildingList.isEmpty) {
      await _getBuildingData();
    }
    var list = await getOldData();
    return list;
  }

  Future<void> _getBuildingData() async {
    try {
      var list = await buildingModel.getBuildingList();
      if (list.isNotEmpty) {
        buildingList = list;
        if(GlobalConfigs.mealUseFilter){

          buildingList.insert(0, FloorEntity(buildingNo: '默认筛选',floorList: [selectFloor!]));
          if(useLastFilter){
            if(!GlobalConfigs.filterBuildingId.isNullOrEmpty()){
              selectBuilding = buildingList.firstWhere((e)=>e.id.toString()==GlobalConfigs.filterBuildingId);
              if(!GlobalConfigs.filterFloorId.isNullOrEmpty()){
                selectFloor = (selectBuilding?.floorList??[]).firstWhere((e)=>e.id.toString()==GlobalConfigs.filterFloorId);
                selectFloor?.iSelected = true;
              }else{
                selectFloor = FloorInfo(floorNo: '默认筛选',isSelected: true);
              }
            }else{
              selectBuilding = list[0];
              selectFloor = FloorInfo(floorNo: '默认筛选',isSelected: true);
            }

          }else{
            selectBuilding = list[0];
            selectFloor = FloorInfo(floorNo: '默认筛选',isSelected: true);
          }
          selectBuilding?.iSelected = true;
          requestRefresh();
        }else{
          if(useLastFilter){
            if(!GlobalConfigs.filterBuildingId.isNullOrEmpty()){
              selectBuilding = buildingList.firstWhere((e)=>e.id.toString()==GlobalConfigs.filterBuildingId);
              selectBuilding?.iSelected = true;
              floorList = selectBuilding?.floorList??[];
              floorList.insert(0, FloorInfo(floorNo: '全部'));
              if(!GlobalConfigs.filterFloorId.isNullOrEmpty()){
                selectFloor = (selectBuilding?.floorList??[]).firstWhere((e)=>e.id.toString()==GlobalConfigs.filterFloorId);
                selectFloor?.iSelected = true;
              }else{
                setFloor();
              }
            }else{
              selectBuilding = list[0];
              selectBuilding?.iSelected = true;
              setFloor();
            }
          }else{
            selectBuilding = list[0];
            selectBuilding?.iSelected = true;
            setFloor();
          }

        }
      }
    } catch (e) {
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  void setFloor() {
    if (selectBuilding != null) {
      floorList = selectBuilding?.copy().floorList??[];

      if (floorList.isEmpty|| floorList.first.floorNo != '全部'&&floorList.first.floorNo != '默认筛选') {
        var first = FloorInfo(
          floorNo: "全部",
        );
        first.iSelected = true;
        floorList.insert(0, first);
        selectFloor = first;
      } else {
        for (var item in floorList) {
          item.isSelected = false;
        }
        floorList.first.isSelected = true;
        selectFloor = floorList.first;
      }
    }
  }

  var inProcess = false;

  Future<List<MedicalElderInfo>> getOldData() async {
    var map = {
      'page': page,
      'rows': pageLength,
      // 'serviceAreaId': widget.serviceAreaId,
      'customerNameOrRoomNoLike': searchName,
      'orderBy': 'room_no',
      'orderByDesc': false, //不传或为false时是正序，传true时是倒序
      // 'isLive': '1'
    };

    if(isMeal){
      map["statusMasterId"] = "0";
    }else{
      map['isLive'] = '1';
    }
    if (!(selectBuilding?.iId??"").isNullOrEmpty()) {
      map['buildingId'] = selectBuilding!.iId;
    }
    if (!(selectFloor?.iId??"").isNullOrEmpty()) {
      map['floorId'] = selectFloor!.iId;
    }

    var url = GlobalConfigs.useArea
        ? HttpApi.areaCustomerElder
        : HttpApi.customerElder;

    if(GlobalConfigs.mealUseFilter){
      url = HttpApi.customerElder;
      if((selectBuilding?.iId??"").isNullOrEmpty()&&searchName.isNullOrEmpty()){
        if(page==1){
          var list = <MedicalElderInfo>[];
          list.addAll(GlobalConfigs.savedFilterElder);
          return list;
        }else{
          return [];
        }
      }
    }
    var data =
        await HttpGo.instance.postData('${url}', data: map,options: PostRequest.urlencodedHeader);

    if (data['code'] == "0") {
      MedicalElderModel model = MedicalElderModel.fromJson(data['data']);
      return model.rows??[];
    } else {
      throw data['msg'];
    }
  }

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if(event.msgCode==MessageConfig.NFC_READ_IC_CARD){
      var cardNumber = event.obj as String;
      getCustomerByCard(cardNumber);
    }
  }

  Future<void> getCustomerByCard(String cardNumber) async {
    showLoadingDialog();
    try{
      var old = await customerModel.getCardAccount(physicalCardNo: cardNumber);
      hideDialog();
      if(old.data!=null){
        var info = await customerModel.getElderInfo(old.data!.human!.id.toString());
        if(selectListener!=null){
          selectListener!(MedicalElderInfo.fromJson(info.toJson()));
        }
      }else{
        showToast("未查询到卡信息");
      }
    }catch(e){
      showToast(e.toNetError());
      hideDialog();
    }
  }

  @override
  void onCreated() {
    super.onCreated();
    requestRefresh();
  }

  // var inProcess = false;
  // @override
  // Future<void> requestRefresh({bool showAni = true}) async {
  //   if(inProcess){
  //     return null;
  //   }
  //   inProcess = true;
  //   var result = await super.requestRefresh(showAni: showAni);
  //   inProcess = false;
  //   return result;
  // }
}
